﻿using Hinacom.Scheduler.Configuration;
using System;
using System.Linq;
using System.Windows.Forms;
using System.Text;

namespace Hinacom.Scheduler.Manager.Views
{
    public partial class SimpleScheduleView : UserControl, IScheduleView
    {
        public SimpleScheduleView()
        {
            InitializeComponent();
        }

        void IScheduleView.ApplyJobInfo(JobInfo jobInfo)
        {
            if (!(jobInfo is SimpleJobInfo))
                throw new Exception("Type mismatch.");
            SimpleJobInfo job = (SimpleJobInfo)jobInfo;

            if (job.RepeatCount == 0)
                rdoRunOnce.Checked = true;
            else if (job.RepeatCount < 0)
                rdoRepeatForever.Checked = true;
            else
            {
                rdoRepeatCount.Checked = true;
                nmbRepeatCount.Value = job.RepeatCount;
            }

            itvInterval.Interval = job.Interval;
        }

        JobInfo IScheduleView.CreateJobInfoInstance()
        {
            return new SimpleJobInfo();
        }

        void IScheduleView.FillJobInfo(JobInfo jobInfo)
        {
            if (!(jobInfo is SimpleJobInfo))
                throw new Exception("Type mismatch.");
            SimpleJobInfo job = (SimpleJobInfo)jobInfo;

            if (rdoRepeatCount.Checked)
                job.RepeatCount = Convert.ToInt32(nmbRepeatCount.Value);
            else if (rdoRepeatForever.Checked)
                job.RepeatCount = -1;
            else
                job.RepeatCount = 0;

            job.Interval = itvInterval.Interval;
        }

        bool IScheduleView.ValidateInput(StringBuilder messages)
        {
            bool valid = true;
            bool runonce = rdoRunOnce.Checked;
            if (!runonce && itvInterval.Interval.Ticks == 0)
            {
                valid = false;
                messages.AppendLine("Please specify the repeat interval.");
            }
            return valid;
        }
    }
}
